import pandas as pd
import numpy as np
from scipy import stats
"""
numpy.mean
算术平均值

numpy.average
加权平均数

scipy.stats.hmean
谐波平均值

scipy.stats.gmean
几何平均数
"""
names={
'count':"总数量",
 'gmean':"几何平均",
 'skew':"偏度",
 'kurtosis':"峰度",
 'median':"中位数",
 'mode':"众数",
 'var':"方差",
 'mean_deviation':"平均偏差",
 'mean':"平均值",
 'std':"标准差",
 'min':"最小值",
 'max':"最大值",
 'R':"范围",
 'IQR':"四分位数",
'IQR_max':"箱体上限",
'IQR_min':"箱体下限"
}
def statistics_info(v,isname=True,percentiles=[],sample=[],isdf=False):
    if sample:
        data={"全部":v}
        for i in sample:
            k="最近"+str(i)
            data[k]=v[-i:]
        rst={}
        for k,vv in data.items():
            rst[k]=statistics_info_one(v=vv,isname=isname,percentiles=percentiles)
        if isdf:
            rst=pd.DataFrame(rst)
        return rst
    else:
        rst= statistics_info_one(v=v,isname=isname,percentiles=percentiles)
        rst=pd.Series(rst)
        rst=pd.DataFrame(rst)
        return rst

def statistics_info_one(v,isname=True,percentiles=[],mode=2):
    rst = {}
    rst["count"] = len(v)
    try:
        # rst["gmean"] = stats.gmean(v)
        if mode>1:
            rst["skew"] = stats.skew(v)
            rst["kurtosis"] = stats.kurtosis(v)
        if isinstance(v,pd.Series):
            v1=v
        else:
            v1 = pd.Series(v)
        rst["median"] = v1.median()
        if mode>1:
            mean = v1.mean()
            rst["var"] = v1.var()
            rst["mean_deviation"] = abs(v1 - mean).mean()
            m = v1.mode()
            if len(m) > 2:
                rst["mode"] = None
            else:
                rst["mode"] = m[0]
        percentiles0=[0.25,0.75]
        for i in percentiles:
            percentiles0.append(i/100)
        v1 = v1.describe(percentiles=percentiles0)
        v1 = v1.to_dict()
        for k1, v1 in v1.items():
            # k1 = k1.replace("%", "p")
            if pd.isna(v1):
                rst[k1] = None
            else:
                rst[k1] = v1
        rst["R"] = rst["max"] - rst["min"]
        rst["IQR"] = rst["75%"] - rst["25%"]
        rst["IQR_max"] = rst["75%"]+1.5*rst["IQR"]
        rst["IQR_min"] = rst["25%"] - 1.5 * rst["IQR"]
        if isname:
            rst0={}
            for k,v in rst.items():
                if k in names:
                    kk=names[k]+"("+k+")"
                elif "%" in k:
                    kk = k.replace("%","分位数") + "(" + k + ")"
                else:
                    kk=k
                rst0[kk]=v
            rst=rst0
    except Exception as e:
        print(e,rst,v)
    return rst